2;
/**
 * create by young (young2f@outlook.com) on 2024/4/21
 */
'use strict';
const base = require('../base/controllerBase');
const moment = require('moment');
const _ = require('lodash');
const { tenantCode } = require('../base/modelBase');

class WorkController extends base {
  async createWork() {
    const { ctx, service } = this;
    try {
      const { body } = ctx.request;
      const model = {
        tenantCode: { type: 'string' },
        code: { type: 'string' },
      };
      ctx.validate(model, body);
      console.log('create work', body);
      const result = await service['workService'].createWork(body);
      ctx.body = { status: 'ok', result };
      ctx.status = 200;
    } catch (e) {
      console.error(e);
      const _message = e && e.message ? e.message : this.ERROR_MSG;
      ctx.body = { status: 'error', message: _message, result: e };
      ctx.status = 200;
    }
  }


  async deleteWork() {
    const { ctx, service } = this;
    try {
      const { body } = ctx.request;
      const model = {
        tenantCode: { type: 'string' },
        code: { type: 'string' },
      };
      ctx.validate(model, body);
      const { code, tenantCode } = body;

      const childWorks = await ctx.app.dbs.find('Work', { workCode: code, tenantCode });
      _.map(childWorks, async work => {
        const result1 = await ctx.app.dbs.find('Work', { workCode: work.code, tenantCode });
        if (result1.length > 0) {
          throw new Error(`子任务已有分配，正在处理，不可删除！`);
        }
      });

      const result1 = await ctx.app.dbs.deleteOne('Work', { code, tenantCode });
      const result = result1 && await ctx.app.dbs.deleteMany('Work', { workCode: code, tenantCode });
      ctx.body = { status: 'ok', result };
      ctx.status = 200;
    } catch (e) {
      console.error(e);
      const _message = e && e.message ? e.message : this.ERROR_MSG;
      ctx.body = { status: 'error', message: _message, result: e };
      ctx.status = 200;
    }
  }

  async updateWork() {
    const { ctx, service } = this;
    try {
      const { body } = ctx.request;
      const model = {
        tenantCode: { type: 'string' },
        code: { type: 'string' },
      };
      ctx.validate(model, body);
      const { code, tenantCode, workList = [] } = body;
      delete body['_id'];

      const childWorks = await ctx.app.dbs.find('Work', { workCode: code, tenantCode });
      _.map(childWorks, async work => {
        const result1 = await ctx.app.dbs.find('Work', { workCode: work.code, tenantCode });
        if (result1.length > 0) {
          throw new Error(`子任务已有分配，正在处理，不可修改！`);
        }
      });


      const result = await ctx.app.dbs.updateOne('Work', { code, tenantCode }, body);
      const oldList = await ctx.app.dbs.find('Work', { tenantCode, workCode: code });

      //先创建，，再更新，再删除
      _.map(workList, async item => {
        const query = { tenantCode, workCode: body.code, code: item.code };
        const temp = await ctx.app.dbs.find('Work', query);
        if (temp.length === 0) {
          //没有，创建
          item.workCode = body.code;
          item.tenantCode = tenantCode;
          delete item['_id'];
          const result = await ctx.app.dbs.insert('Work', item);
        } else {
          //更新
          console.log('更新item', item);
          delete item['_id'];
          const result = await ctx.app.dbs.updateOne('Work', { code: item.code }, item);
        }
      });
      //再删除

      _.map(oldList, async work => {
        const temp = _.find(workList, item => {
          return item.code === work.code;
        });
        if (!temp) {
          const result = await ctx.app.dbs.deleteOne('Work', { code: work.code });
        }
      });
      ctx.body = { status: 'ok', result };
      ctx.status = 200;
    } catch (e) {
      console.error(e);
      const _message = e && e.message ? e.message : this.ERROR_MSG;
      ctx.body = { status: 'error', message: _message, result: e };
      ctx.status = 200;
    }
  }

  async findWork() {
    const { ctx, service } = this;
    try {
      const { body } = ctx.request;
      const model = {
        tenantCode: { type: 'string' },
        code: { type: 'string' },
      };
      ctx.validate(model, body);
      const { code, tenantCode } = body;

      const workList = await ctx.app.dbs.find('Work', { workCode: code, tenantCode });
      const result = await ctx.app.dbs.findOne('Work', { code: code, tenantCode });
      result.workList = workList;

      ctx.body = { status: 'ok', result };
      ctx.status = 200;
    } catch (e) {
      console.error(e);
      const _message = e && e.message ? e.message : this.ERROR_MSG;
      ctx.body = { status: 'error', message: _message, result: e };
      ctx.status = 200;
    }
  }

  async findWorkMany() {
    const { ctx, service } = this;
    try {
      const { body } = ctx.request;
      const model = {
        tenantCode: { type: 'string' },
      };
      console.log('find work many', body);
      ctx.validate(model, body);
      const {
        tenantCode, userType,
        username, workUsername, offlineMan, workName,
        userCode,
        desc, isAdmin,
        isEnded, isOverdue,
        createdTs, code, adminCode,
      } = body;
      const query = { tenantCode };
      if (createdTs && createdTs.length > 0) {
        query['createdTs'] = {
          $gte: new Date(moment(createdTs[0])
            .valueOf()),
          $lt: new Date(moment(createdTs[1])
            .valueOf())
        };
      }
      if (isEnded !== undefined) {
        query['isEnded'] = isEnded;
      }
      const curTimeStr =moment().add(-1,"days").format('YYYY-MM-DD')+" 23:59:59";
      console.log('isOverdue', isOverdue);
      if (isOverdue !== undefined && isOverdue === '未逾期') {
        query['requiredCompletionDate'] = { $gt: new Date(moment(curTimeStr)) };
      }
      if (isOverdue !== undefined && isOverdue === '已逾期') {
        query['requiredCompletionDate'] = { $lt: new Date(moment(curTimeStr)) };
      }
      desc ? query['desc'] = { $regex: desc } : undefined;
      code ? query['code'] = { $regex: code } : undefined;
      adminCode ? query['adminCode'] = { $regex: adminCode } : undefined;
      workUsername ? query['workList.username'] = { $regex: workUsername } : undefined;
      offlineMan ? query['workList.offlineMan'] = { $regex: offlineMan } : undefined;
      workName ? query['workName'] = { $regex: workName } : undefined;
      /**
       * 管理员查找
       */
      if (isAdmin) {
        !adminCode ? query['isAdmin'] = true : undefined;
        body.createUser ? query['createUser'] = body.createUser : undefined;
        console.log(query);
        const result = await ctx.app.dbs.find('Work', query);
        ctx.body = { status: 'ok', result };
        ctx.status = 200;
        return;
      }

      /**
       * 普通用户查找
       * @type {{tenantCode: *}}
       */
      delete query['idAdmin'];
      delete query['createUser'];
      query['userCode'] = body.userCode;
      const result1 = await ctx.app.dbs.find('Work', query);
      // console.log('find works11', result1);
      ctx.body = { status: 'ok', result: result1 };
      ctx.status = 200;

      if (userType === 'admin') {
        query['createUser'] = username;
        query['isAdmin'] = true;
      } else {
        query['userCode'] = userCode;
      }
      const result = await ctx.app.dbs.find('Work', query);
      ctx.body = { status: 'ok', result };
      ctx.status = 200;
    } catch (e) {
      console.error(e);
      const _message = e && e.message ? e.message : this.ERROR_MSG;
      ctx.body = { status: 'error', message: _message, result: e };
      ctx.status = 200;
    }
  }

  /**
   * 完成任务
   * @returns {Promise<void>}
   */
  async endWork() {
    const { ctx, service } = this;
    try {
      const { body } = ctx.request;
      const model = {
        tenantCode: { type: 'string' },
        isEnded: { type: 'boolean' },
        code: { type: 'string' },
      };

      ctx.validate(model, body);
      const {
        tenantCode,
        code,
      } = body;
      const query = { tenantCode, code };
      const result = await ctx.app.dbs.updateOne('Work', query, body);

      ctx.body = { status: 'ok', result };
      ctx.status = 200;
    } catch (e) {
      console.error(e);
      const _message = e && e.message ? e.message : this.ERROR_MSG;
      ctx.body = { status: 'error', message: _message, result: e };
      ctx.status = 200;
    }
  }


  async createWorkTimer() {
    const { ctx, service } = this;
    try {
      const { body } = ctx.request;
      const model = {
        tenantCode: { type: 'string' },
        code: { type: 'string' },
      };
      ctx.validate(model, body);
      const { workList = [], code, tenantCode } = body;
      _.map(workList, async work => {
        work.workCode = code;
        work.tenantCode = tenantCode;
        const result = await ctx.app.dbs.insert('WorkTimer', work);
      });
      const result = await ctx.app.dbs.insert('WorkTimer', body);
      ctx.body = { status: 'ok', result };
      ctx.status = 200;
    } catch (e) {
      console.error(e);
      const _message = e && e.message ? e.message : this.ERROR_MSG;
      ctx.body = { status: 'error', message: _message, result: e };
      ctx.status = 200;
    }
  }


  async deleteWorkTimer() {
    const { ctx, service } = this;
    try {
      const { body } = ctx.request;
      const model = {
        tenantCode: { type: 'string' },
        code: { type: 'string' },
      };
      ctx.validate(model, body);
      const { code, tenantCode } = body;

      const childWorks = await ctx.app.dbs.find('WorkTimer', { workCode: code, tenantCode });
      _.map(childWorks, async work => {
        const result1 = await ctx.app.dbs.find('WorkTimer', { workCode: work.code, tenantCode });
        if (result1.length > 0) {
          throw new Error(`子任务已有分配，正在处理，不可删除！`);
        }
      });

      const result1 = await ctx.app.dbs.deleteOne('WorkTimer', { code, tenantCode });
      const result = result1 && await ctx.app.dbs.deleteMany('WorkTimer', { workCode: code, tenantCode });
      ctx.body = { status: 'ok', result };
      ctx.status = 200;
    } catch (e) {
      console.error(e);
      const _message = e && e.message ? e.message : this.ERROR_MSG;
      ctx.body = { status: 'error', message: _message, result: e };
      ctx.status = 200;
    }
  }

  async updateWorkTimer() {
    const { ctx, service } = this;
    try {
      const { body } = ctx.request;
      const model = {
        tenantCode: { type: 'string' },
        code: { type: 'string' },
      };
      ctx.validate(model, body);
      const { code, tenantCode, workList = [] } = body;
      delete body['_id'];

      const result = await ctx.app.dbs.updateOne('WorkTimer', { code, tenantCode }, body);

      ctx.body = { status: 'ok', result };
      ctx.status = 200;
    } catch (e) {
      console.error(e);
      const _message = e && e.message ? e.message : this.ERROR_MSG;
      ctx.body = { status: 'error', message: _message, result: e };
      ctx.status = 200;
    }
  }

  async findWorkTimer() {
    const { ctx, service } = this;
    try {
      const { body } = ctx.request;
      const model = {
        tenantCode: { type: 'string' },
        code: { type: 'string' },
      };
      ctx.validate(model, body);
      const { code, tenantCode } = body;

      const workList = await ctx.app.dbs.find('WorkTimer', { workCode: code, tenantCode });
      const result = await ctx.app.dbs.findOne('WorkTimer', { code: code, tenantCode });
      result.workList = workList;

      ctx.body = { status: 'ok', result };
      ctx.status = 200;
    } catch (e) {
      console.error(e);
      const _message = e && e.message ? e.message : this.ERROR_MSG;
      ctx.body = { status: 'error', message: _message, result: e };
      ctx.status = 200;
    }
  }

  async findWorkTimerMany() {
    const { ctx, service } = this;
    try {
      const { body } = ctx.request;
      const model = {
        tenantCode: { type: 'string' },
      };
      console.log('find workTimer body', body);
      ctx.validate(model, body);
      const {
        tenantCode, userType,
        username, workUsername, offlineMan, workName,
        userCode,
        desc, isAdmin,
        isEnded,
        createdTs, code, adminCode,
      } = body;
      const query = { tenantCode };
      if (createdTs && createdTs.length > 0) {
        query['createdTs'] = {
          $gte: new Date(moment(createdTs[0])
            .valueOf()),
          $lt: new Date(moment(createdTs[1])
            .valueOf())
        };
      }

      desc ? query['desc'] = { $regex: desc } : undefined;
      code ? query['code'] = { $regex: code } : undefined;
      // adminCode ? query['adminCode'] = { $regex: adminCode } : undefined;
      workUsername ? query['workList.username'] = { $regex: workUsername } : undefined;
      offlineMan ? query['workList.offlineMan'] = { $regex: offlineMan } : undefined;
      workName ? query['workName'] = { $regex: workName } : undefined;

      body.createUser ? query['createUser'] = body.createUser : undefined;
      console.log('find works qqq', query);
      const result = await ctx.app.dbs.find('WorkTimer', query);
      console.log('find works TIMER', result);
      ctx.body = { status: 'ok', result };
      ctx.status = 200;


    } catch (e) {
      console.error(e);
      const _message = e && e.message ? e.message : this.ERROR_MSG;
      ctx.body = { status: 'error', message: _message, result: e };
      ctx.status = 200;
    }
  }
}

module.exports = WorkController;
